Load needed libraries
library(fastDummies)
library(readr)
library(ggplot2)
library(dplyr)
library(caret)
library(glmnet)
library(boot)
library(tree)
library(ranger)
library(xgboost)
library(gbm)
library(vip)
library(ISLR)
library(tidyr)
library(gridExtra)
library(reshape2)
Set the seed for reproducibility
set.seed(1)
Load the dataset
original_lc_data <- read.csv("LCdata.csv",sep = ";")
lc_data <- original_lc_data
Remove attributes not available for prediction
lc_data <- subset(lc_data, select = -c(collection_recovery_fee, installment, issue_d,
last_pymnt_amnt, last_pymnt_d, loan_status,
next_pymnt_d, out_prncp, out_prncp_inv,
pymnt_plan, recoveries, total_pymnt,
total_pymnt_inv,total_rec_int, total_rec_late_fee, total_rec_prncp))
summary(lc_data)
id member_id loan_amnt funded_amnt funded_amnt_inv term int_rate
Min. : 54734 Min. : 70473 Min. : 500 Min. : 500 Min. : 0 Length:798641 Min. : 5.32
1st Qu.: 9207230 1st Qu.:10877939 1st Qu.: 8000 1st Qu.: 8000 1st Qu.: 8000 Class :character 1st Qu.: 9.99
Median :34433372 Median :37095300 Median :13000 Median :13000 Median :13000 Mode :character Median :12.99
Mean :32463636 Mean :35000265 Mean :14754 Mean :14741 Mean :14702 Mean :13.24
3rd Qu.:54900100 3rd Qu.:58470266 3rd Qu.:20000 3rd Qu.:20000 3rd Qu.:20000 3rd Qu.:16.20
Max. :68617057 Max. :73544841 Max. :35000 Max. :35000 Max. :35000 Max. :28.99
emp_title emp_length home_ownership annual_inc verification_status url
Length:798641 Length:798641 Length:798641 Min. : 0 Length:798641 Length:798641
Class :character Class :character Class :character 1st Qu.: 45000 Class :character Class :character
Mode :character Mode :character Mode :character Median : 65000 Mode :character Mode :character
Mean : 75014
3rd Qu.: 90000
Max. :9500000
NA's :4
desc purpose title zip_code addr_state dti
Length:798641 Length:798641 Length:798641 Length:798641 Length:798641 Min. : 0.00
Class :character Class :character Class :character Class :character Class :character 1st Qu.: 11.91
Mode :character Mode :character Mode :character Mode :character Mode :character Median : 17.66
Mean : 18.16
3rd Qu.: 23.95
Max. :9999.00
delinq_2yrs earliest_cr_line inq_last_6mths mths_since_last_delinq mths_since_last_record open_acc
Min. : 0.0000 Length:798641 Min. : 0.0000 Min. : 0.0 Min. : 0.0 Min. : 0.00
1st Qu.: 0.0000 Class :character 1st Qu.: 0.0000 1st Qu.: 15.0 1st Qu.: 51.0 1st Qu.: 8.00
Median : 0.0000 Mode :character Median : 0.0000 Median : 31.0 Median : 70.0 Median :11.00
Mean : 0.3145 Mean : 0.6947 Mean : 34.1 Mean : 70.1 Mean :11.55
3rd Qu.: 0.0000 3rd Qu.: 1.0000 3rd Qu.: 50.0 3rd Qu.: 92.0 3rd Qu.:14.00
Max. :39.0000 Max. :33.0000 Max. :188.0 Max. :129.0 Max. :90.00
NA's :25 NA's :25 NA's :408818 NA's :675190 NA's :25
pub_rec revol_bal revol_util total_acc initial_list_status last_credit_pull_d
Min. : 0.0000 Min. : 0 Min. : 0.00 Min. : 1.00 Length:798641 Length:798641
1st Qu.: 0.0000 1st Qu.: 6443 1st Qu.: 37.70 1st Qu.: 17.00 Class :character Class :character
Median : 0.0000 Median : 11876 Median : 56.00 Median : 24.00 Mode :character Mode :character
Mean : 0.1953 Mean : 16930 Mean : 55.05 Mean : 25.27
3rd Qu.: 0.0000 3rd Qu.: 20839 3rd Qu.: 73.50 3rd Qu.: 32.00
Max. :63.0000 Max. :2904836 Max. :892.30 Max. :169.00
NA's :25 NA's :2 NA's :454 NA's :25
collections_12_mths_ex_med mths_since_last_major_derog policy_code application_type annual_inc_joint dti_joint
Min. : 0.00000 Min. : 0.0 Min. :1 Length:798641 Min. : 17950 Min. : 3.0
1st Qu.: 0.00000 1st Qu.: 27.0 1st Qu.:1 Class :character 1st Qu.: 76167 1st Qu.:13.3
Median : 0.00000 Median : 44.0 Median :1 Mode :character Median :101886 Median :17.7
Mean : 0.01447 Mean : 44.1 Mean :1 Mean :110745 Mean :18.4
3rd Qu.: 0.00000 3rd Qu.: 61.0 3rd Qu.:1 3rd Qu.:133000 3rd Qu.:22.6
Max. :20.00000 Max. :188.0 Max. :1 Max. :500000 Max. :43.9
NA's :126 NA's :599107 NA's :798181 NA's :798183
verification_status_joint acc_now_delinq tot_coll_amt tot_cur_bal open_acc_6m open_il_6m
Length:798641 Min. : 0.000000 Min. : 0 Min. : 0 Min. : 0.0 Min. : 0.0
Class :character 1st Qu.: 0.000000 1st Qu.: 0 1st Qu.: 29861 1st Qu.: 0.0 1st Qu.: 1.0
Mode :character Median : 0.000000 Median : 0 Median : 80647 Median : 1.0 Median : 2.0
Mean : 0.005026 Mean : 228 Mean : 139508 Mean : 1.1 Mean : 2.9
3rd Qu.: 0.000000 3rd Qu.: 0 3rd Qu.: 208229 3rd Qu.: 2.0 3rd Qu.: 4.0
Max. :14.000000 Max. :9152545 Max. :8000078 Max. :14.0 Max. :33.0
NA's :25 NA's :63276 NA's :63276 NA's :779525 NA's :779525
open_il_12m open_il_24m mths_since_rcnt_il total_bal_il il_util open_rv_12m open_rv_24m
Min. : 0.0 Min. : 0.0 Min. : 0.0 Min. : 0 Min. : 0.0 Min. : 0.0 Min. : 0
1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 6.0 1st Qu.: 10164 1st Qu.: 58.4 1st Qu.: 0.0 1st Qu.: 1
Median : 0.0 Median : 1.0 Median : 12.0 Median : 24544 Median : 74.8 Median : 1.0 Median : 2
Mean : 0.8 Mean : 1.7 Mean : 21.1 Mean : 36428 Mean : 71.5 Mean : 1.4 Mean : 3
3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 23.0 3rd Qu.: 47640 3rd Qu.: 87.7 3rd Qu.: 2.0 3rd Qu.: 4
Max. :12.0 Max. :19.0 Max. :363.0 Max. :878459 Max. :223.3 Max. :22.0 Max. :43
NA's :779525 NA's :779525 NA's :780030 NA's :779525 NA's :782007 NA's :779525 NA's :779525
max_bal_bc all_util total_rev_hi_lim inq_fi total_cu_tl inq_last_12m
Min. : 0 Min. : 0.0 Min. : 0 Min. : 0.0 Min. : 0.0 Min. :-4
1st Qu.: 2406 1st Qu.: 47.6 1st Qu.: 13900 1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 0
Median : 4502 Median : 61.9 Median : 23700 Median : 0.0 Median : 0.0 Median : 2
Mean : 5878 Mean : 60.8 Mean : 32093 Mean : 0.9 Mean : 1.5 Mean : 2
3rd Qu.: 7774 3rd Qu.: 75.2 3rd Qu.: 39800 3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 3
Max. :83047 Max. :151.4 Max. :9999999 Max. :16.0 Max. :35.0 Max. :32
NA's :779525 NA's :779525 NA's :63276 NA's :779525 NA's :779525 NA's :779525
First we delete the columns which aren’t useful for our prediction
lc_data$id <- NULL
lc_data$member_id <- NULL
lc_data$zip_code <- NULL
lc_data$url <- NULL
Looks like policy_code contains just value equal to 1, it can be removed
lc_data$policy_code <- NULL
Remove additional columns which are related to the historical data
lc_data$last_credit_pull_d <- NULL
Then we delete the columns which can’t be converted to categorical and require NLP
lc_data$title <- NULL
lc_data$desc <- NULL
lc_data$emp_title <- NULL
Let’s examine the loan_amnt column
sum(is.na(lc_data$loan_amnt))
[1] 0
cor(lc_data$loan_amnt, lc_data$int_rate)
[1] 0.1447189
hist(lc_data$loan_amnt, breaks = 20, main = "loan_amnt distribution", xlab = "loan_amnt", col = "lightblue", border = "black")
ggplot(data = lc_data, mapping = aes(x=int_rate,y=loan_amnt)) + geom_boxplot()
Standardize loan_amnt
#lc_data$loan_amnt <- scale(lc_data$loan_amnt)
Let’s examine the funded_amnt column
sum(is.na(lc_data$funded_amnt))
[1] 0
cor(lc_data$funded_amnt, lc_data$int_rate)
[1] 0.1448634
hist(lc_data$funded_amnt, breaks = 20, main = "funded_amnt distribution", xlab = "funded_amnt", col = "lightblue", border = "black")
As we can see, funded_amnt is almost the same as the loan_amnt column, consequently, we remove it.
lc_data$funded_amnt <- NULL
Let’s examine the funded_amnt_inv column
sum(is.na(lc_data$funded_amnt_inv))
[1] 0
cor(lc_data$funded_amnt_inv, lc_data$int_rate)
[1] 0.1449083
hist(lc_data$funded_amnt_inv, breaks = 20, main = "funded_amnt_inv distribution", xlab = "funded_amnt_inv", col = "lightblue", border = "black")
Remove funded_amnt_inv for the same reason as above
lc_data$funded_amnt_inv <- NULL
Let’s see the int_rate distribution.
hist(lc_data$int_rate, breaks = 20, main = "int_rate distribution", xlab = "int_rate", col = "lightblue", border = "black")
Standardize int rate:
#lc_data$int_rate <- scale(lc_data$int_rate)
As we can observe, there are 40363 NAs. We can assume 40363 do not work.
barplot(table(lc_data$emp_length),
xlab = "emp_length years",
ylab = "Frequency",
col = "skyblue",
border = "black",
cex.names = 0.6) # The size of the main title
Since emp_length seems to be categorical, we transform it to as a factor and then as numeric. The conversion to numeric is needed for supporting the XGBoost
lc_data$emp_length <- as.factor(lc_data$emp_length)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=emp_length)) + geom_boxplot()
lc_data$emp_length <- as.numeric(lc_data$emp_length)
As we can see, term plays a crucial role in predicting the interest rate.
lc_data$term <- as.factor(lc_data$term)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=term)) + geom_boxplot()
lc_data$term <- as.numeric(lc_data$term)
Cleaning of home_ownership:
During the data cleaning phase, our analysis revealed that the variable “home_ownership” does not show a distinct correlation with interest rates. Specifically, among the categories, “ANY” and “OTHER” contain 2 and 154 cases, respectively, while the “NONE” category comprises 39 cases. Although the “NONE” category appears to demonstrate a higher interest rate compared to others, the limited sample size of 39 cases raises doubts about the reliability of this observation. Notably, the “NONE” category might pertain to individuals experiencing homelessness, prompting ethical concerns about loan provision to this demographic.
table(lc_data$home_ownership)
ANY MORTGAGE NONE OTHER OWN RENT
2 399151 45 155 78789 320499
ggplot(data = lc_data, mapping = aes(x=int_rate,y=home_ownership)) + geom_boxplot()
Then, we retain mortgage, own and rent:
lc_data <- lc_data %>% filter(home_ownership %in% c("MORTGAGE","OWN","RENT"))
lc_data$home_ownership <- as.numeric(as.factor(lc_data$home_ownership))
Application joint handling:
# merging annual income
lc_data <- lc_data %>% mutate(
annual_inc_merged = ifelse(is.na(annual_inc_joint)== TRUE, annual_inc,annual_inc_joint))
lc_data <- lc_data %>% select(-annual_inc,-annual_inc_joint)
# merging debt to income ratio
lc_data <- lc_data %>% mutate(
dti_merged = ifelse(is.na(dti_joint)== TRUE, dti,dti_joint))
lc_data <- lc_data %>% select(-dti,-dti_joint)
Upon reviewing the summary again, it becomes apparent that there are merely 460 joint applications, constituting a small subset within the extensive dataset of around 800k rows. Through consolidating the debt-to-income ratios (dti’s), we can pinpoint the data pertinent to our research objectives. Hence, it is advisable to eliminate the columns verification_status_joint and application_type to prevent introducing unwarranted variability into our analysis.
table(lc_data$verification_status)
Not Verified Source Verified Verified
240255 296631 261553
table(lc_data$verification_status_joint)
Not Verified Source Verified Verified
797979 253 53 154
lc_data$verification_status <- as.numeric(as.factor(lc_data$verification_status))
lc_data <- lc_data %>% select(-verification_status_joint, -application_type)
Let’s check if other is NA or a real value for purpose. It’s a real one, so we don’t have to handle it.
lc_data$purpose <- as.factor(lc_data$purpose)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=purpose)) + geom_boxplot()
lc_data$purpose <- as.numeric(lc_data$purpose)
Let’s have a glance to the state address:
table(lc_data$addr_state)
AK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN KS
1992 10101 5953 18359 116578 16934 12154 2188 2268 54819 26146 4112 13 11 31880 12393 7105
KY LA MA MD ME MI MN MO MS MT NC ND NE NH NJ NM NV
7726 9498 18546 18906 469 20678 14306 12821 3455 2286 22135 431 1064 3865 29991 4428 11155
NY OH OK OR PA RI SC SD TN TX UT VA VT WA WI WV WY
66790 26682 7266 9806 28221 3499 9609 1615 11618 63982 5629 23616 1606 17470 10446 3977 1841
lc_data$addr_state <- as.factor(lc_data$addr_state)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=addr_state)) + geom_boxplot()
lc_data$addr_state <- as.numeric(lc_data$addr_state)
Regarding delinquency in the last 2 years, there are few NAs then remove them:
lc_data <- lc_data %>%
filter(!(is.na(delinq_2yrs)))
The columns mths_since_delinq_cat, mths_since_last_record, mths_since_rcnt_il and mths_since_last_major_derog contain numerical values which refer to the number of the months. Since this columns contain a lot of null values which can’t be replaced with 0’s, one of the most appropriate operations that can be made is applying discretization. We do this by creating a set of contiguous bins based on years, while for the null values we create a separate bin.
lc_data <- lc_data %>%
mutate(mths_since_delinq_cat = ifelse(
is.na(mths_since_last_delinq) == TRUE,
"NONE",
ifelse(
mths_since_last_delinq <= 12,
"Less_1_Y",
ifelse(
mths_since_last_delinq <= 24,
"Less_2_Y",
ifelse(
mths_since_last_delinq <= 36,
"Less_3_Y",
ifelse(mths_since_last_delinq <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_delinq)
lc_data$mths_since_delinq_cat <- as.factor(lc_data$mths_since_delinq_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_delinq_cat))+geom_boxplot()
lc_data$mths_since_delinq_cat <- as.numeric(lc_data$mths_since_delinq_cat)
lc_data <- lc_data %>%
mutate(mths_since_last_record_cat = ifelse(
is.na(mths_since_last_record) == TRUE,
"NONE",
ifelse(
mths_since_last_record <= 12,
"Less_1_Y",
ifelse(
mths_since_last_record <= 24,
"Less_2_Y",
ifelse(
mths_since_last_record <= 36,
"Less_3_Y",
ifelse(mths_since_last_record <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_record)
lc_data$mths_since_last_record_cat <- as.factor(lc_data$mths_since_last_record_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_record_cat))+geom_boxplot()
lc_data$mths_since_last_record_cat <- as.numeric(lc_data$mths_since_last_record_cat)
lc_data <-lc_data %>%
mutate(mths_since_rcnt_il_cat = ifelse(
is.na(mths_since_rcnt_il) == TRUE,
"NONE",
ifelse(
mths_since_rcnt_il <= 12,
"Less_1_Y",
ifelse(
mths_since_rcnt_il <= 24,
"Less_2_Y",
ifelse(
mths_since_rcnt_il <= 36,
"Less_3_Y",
ifelse(mths_since_rcnt_il <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_rcnt_il)
lc_data$mths_since_rcnt_il_cat <- as.factor(lc_data$mths_since_rcnt_il_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_rcnt_il_cat))+geom_boxplot()
lc_data$mths_since_rcnt_il_cat <- as.numeric(lc_data$mths_since_rcnt_il_cat)
lc_data <-lc_data %>%
mutate(mths_since_last_major_derog_cat = ifelse(
is.na(mths_since_last_major_derog) == TRUE,
"NONE",
ifelse(
mths_since_last_major_derog <= 12,
"Less_1_Y",
ifelse(
mths_since_last_major_derog <= 24,
"Less_2_Y",
ifelse(
mths_since_last_major_derog <= 36,
"Less_3_Y",
ifelse(mths_since_last_major_derog <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_major_derog)
lc_data$mths_since_last_major_derog_cat <- as.factor(lc_data$mths_since_last_major_derog_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_major_derog_cat))+geom_boxplot()
lc_data$mths_since_last_major_derog_cat <- as.numeric(lc_data$mths_since_last_major_derog_cat)
The variable initial_list_status identifies whether a loan was initially listed in the whole (W) or fractional (F) market. This variable could be useful so we can keep it and transform it to a factor and then to a numeric value, for the same purpose of compatibility with the XGBoost function.
lc_data$initial_list_status <- as.factor(lc_data$initial_list_status)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=initial_list_status))+geom_boxplot()
lc_data$initial_list_status <- as.numeric(lc_data$initial_list_status)
Let’s check which columns still have null values
colSums(is.na(lc_data))
loan_amnt term int_rate
0 0 0
emp_length home_ownership verification_status
0 0 0
purpose addr_state delinq_2yrs
0 0 0
earliest_cr_line inq_last_6mths open_acc
0 0 0
pub_rec revol_bal revol_util
0 2 428
total_acc initial_list_status collections_12_mths_ex_med
0 0 99
acc_now_delinq tot_coll_amt tot_cur_bal
0 63132 63132
open_acc_6m open_il_6m open_il_12m
779302 779302 779302
open_il_24m total_bal_il il_util
779302 779302 781784
open_rv_12m open_rv_24m max_bal_bc
779302 779302 779302
all_util total_rev_hi_lim inq_fi
779302 63132 779302
total_cu_tl inq_last_12m annual_inc_merged
779302 779302 0
dti_merged mths_since_delinq_cat mths_since_last_record_cat
0 0 0
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
0 0
The columns revol_bal and revol_util contain only few NA values, those values can’t be replaced with 0, then we filter the values which are not NAs.
lc_data <- lc_data %>%
filter(!(is.na(revol_bal))) %>%
filter(!(is.na(revol_util)))
Let’s check which columns still have null values:
names(which(colSums(is.na(lc_data)) > 0))
[1] "collections_12_mths_ex_med" "tot_coll_amt" "tot_cur_bal" "open_acc_6m"
[5] "open_il_6m" "open_il_12m" "open_il_24m" "total_bal_il"
[9] "il_util" "open_rv_12m" "open_rv_24m" "max_bal_bc"
[13] "all_util" "total_rev_hi_lim" "inq_fi" "total_cu_tl"
[17] "inq_last_12m"
Replace null values with 0 where is possible
lc_data <-
lc_data %>%
mutate(open_acc_6m = ifelse(is.na(open_acc_6m) == TRUE, 0, open_acc_6m)) %>%
mutate(tot_cur_bal = ifelse(is.na(tot_cur_bal) == TRUE, 0, tot_cur_bal)) %>%
mutate(open_il_6m = ifelse(is.na(open_il_6m) == TRUE, 0, open_il_6m)) %>%
mutate(open_il_12m = ifelse(is.na(open_il_12m) == TRUE, 0, open_il_12m)) %>%
mutate(open_il_24m = ifelse(is.na(open_il_24m) == TRUE, 0, open_il_24m)) %>%
mutate(total_bal_il = ifelse(is.na(total_bal_il) == TRUE, 0, total_bal_il)) %>%
mutate(il_util = ifelse(is.na(il_util) == TRUE, 0, il_util)) %>%
mutate(open_rv_12m = ifelse(is.na(open_rv_12m) == TRUE, 0, open_rv_12m)) %>%
mutate(total_rev_hi_lim = ifelse(is.na(total_rev_hi_lim) == TRUE, 0, total_rev_hi_lim)) %>%
mutate(max_bal_bc = ifelse(is.na(max_bal_bc) == TRUE, 0, max_bal_bc)) %>%
mutate(all_util = ifelse(is.na(all_util) == TRUE, 0, all_util)) %>%
mutate(inq_fi = ifelse(is.na(inq_fi) == TRUE, 0, inq_fi)) %>%
mutate(total_cu_tl = ifelse(is.na(total_cu_tl) == TRUE, 0, total_cu_tl)) %>%
mutate(inq_last_12m = ifelse(is.na(inq_last_12m) == TRUE, 0, inq_last_12m)) %>%
mutate(open_rv_24m = ifelse(is.na(open_rv_24m) == TRUE, 0, open_rv_24m)) %>%
mutate(tot_coll_amt = ifelse(is.na(tot_coll_amt)== TRUE,0, tot_coll_amt)) %>%
mutate(collections_12_mths_ex_med = ifelse(is.na(collections_12_mths_ex_med)== TRUE,0, collections_12_mths_ex_med))
earliest_cr_line contains the month the borrower’s earliest reported credit line was opened. Even if this date consists only on month and year, still there are too many unique values. We could transform the dates in to a numerical value, by converting them from date into Unix Time. This unit measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. Since this column doesn’t contain the day number, we take as a reference the first day of the month.
lc_data <- lc_data %>%
filter(!(is.na(earliest_cr_line)))
# function to replace dates with unix time
to_unix_time <- function(date) {
tmp <- paste("01", date, sep="-")
return (as.numeric(as.POSIXct(tmp, format="%d-%b-%Y", tz="UTC")))
}
# map dates to unix time
lc_data$earliest_cr_line <- apply(lc_data, 1, function(row) to_unix_time(row["earliest_cr_line"]))
# standardize them
#lc_data$earliest_cr_line <- scale(lc_data$earliest_cr_line)
Outliers Removal:
boxplot(lc_data$int_rate)
# Identify outliers using boxplot
outliers <- boxplot(lc_data$int_rate, plot = FALSE)$out
# Remove outliers from the dataset
lc_data_clean <- lc_data[!lc_data$int_rate %in% outliers, ]
summary(lc_data)
loan_amnt term int_rate emp_length home_ownership verification_status purpose
Min. : 500 Min. :1.0 Min. : 5.32 Min. : 1.00 Min. :1.000 Min. :1.000 Min. : 1.000
1st Qu.: 8000 1st Qu.:1.0 1st Qu.: 9.99 1st Qu.: 3.00 1st Qu.:1.000 1st Qu.:1.000 1st Qu.: 3.000
Median :13000 Median :1.0 Median :12.99 Median : 4.00 Median :2.000 Median :2.000 Median : 3.000
Mean :14757 Mean :1.3 Mean :13.24 Mean : 5.11 Mean :1.901 Mean :2.027 Mean : 3.571
3rd Qu.:20000 3rd Qu.:2.0 3rd Qu.:16.20 3rd Qu.: 7.00 3rd Qu.:3.000 3rd Qu.:3.000 3rd Qu.: 3.000
Max. :35000 Max. :2.0 Max. :28.99 Max. :12.00 Max. :3.000 Max. :3.000 Max. :14.000
addr_state delinq_2yrs earliest_cr_line inq_last_6mths open_acc pub_rec
Min. : 1.00 Min. : 0.0000 Min. :-820540800 Min. : 0.0000 Min. : 1.00 Min. : 0.0000
1st Qu.:10.00 1st Qu.: 0.0000 1st Qu.: 770428800 1st Qu.: 0.0000 1st Qu.: 8.00 1st Qu.: 0.0000
Median :24.00 Median : 0.0000 Median : 936144000 Median : 0.0000 Median :11.00 Median : 0.0000
Mean :24.14 Mean : 0.3143 Mean : 889273164 Mean : 0.6947 Mean :11.55 Mean : 0.1954
3rd Qu.:37.00 3rd Qu.: 0.0000 3rd Qu.:1051747200 3rd Qu.: 1.0000 3rd Qu.:14.00 3rd Qu.: 0.0000
Max. :51.00 Max. :39.0000 Max. :1351728000 Max. :33.0000 Max. :90.00 Max. :63.0000
revol_bal revol_util total_acc initial_list_status collections_12_mths_ex_med acc_now_delinq
Min. : 0 Min. : 0.00 Min. : 1.00 Min. :1.000 Min. : 0.00000 Min. : 0.000000
1st Qu.: 6450 1st Qu.: 37.70 1st Qu.: 17.00 1st Qu.:1.000 1st Qu.: 0.00000 1st Qu.: 0.000000
Median : 11881 Median : 56.00 Median : 24.00 Median :1.000 Median : 0.00000 Median : 0.000000
Mean : 16934 Mean : 55.05 Mean : 25.27 Mean :1.485 Mean : 0.01448 Mean : 0.005026
3rd Qu.: 20844 3rd Qu.: 73.50 3rd Qu.: 32.00 3rd Qu.:2.000 3rd Qu.: 0.00000 3rd Qu.: 0.000000
Max. :2904836 Max. :892.30 Max. :169.00 Max. :2.000 Max. :20.00000 Max. :14.000000
tot_coll_amt tot_cur_bal open_acc_6m open_il_6m open_il_12m open_il_24m
Min. : 0 Min. : 0 Min. : 0.00000 Min. : 0.00000 Min. : 0.00000 Min. : 0.00000
1st Qu.: 0 1st Qu.: 23195 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000
Median : 0 Median : 65402 Median : 0.00000 Median : 0.00000 Median : 0.00000 Median : 0.00000
Mean : 210 Mean : 128461 Mean : 0.02641 Mean : 0.06982 Mean : 0.01816 Mean : 0.03991
3rd Qu.: 0 3rd Qu.: 195864 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000
Max. :9152545 Max. :8000078 Max. :14.00000 Max. :33.00000 Max. :12.00000 Max. :19.00000
total_bal_il il_util open_rv_12m open_rv_24m max_bal_bc all_util
Min. : 0 Min. : 0.000 Min. : 0.00000 Min. : 0.00000 Min. : 0.0 Min. : 0.000
1st Qu.: 0 1st Qu.: 0.000 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.0 1st Qu.: 0.000
Median : 0 Median : 0.000 Median : 0.00000 Median : 0.00000 Median : 0.0 Median : 0.000
Mean : 872 Mean : 1.489 Mean : 0.03316 Mean : 0.07114 Mean : 140.8 Mean : 1.456
3rd Qu.: 0 3rd Qu.: 0.000 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.0 3rd Qu.: 0.000
Max. :878459 Max. :223.300 Max. :22.00000 Max. :43.00000 Max. :83047.0 Max. :151.400
total_rev_hi_lim inq_fi total_cu_tl inq_last_12m annual_inc_merged dti_merged
Min. : 0 Min. : 0.00000 Min. : 0.00000 Min. :-4.00000 Min. : 1896 Min. : 0.00
1st Qu.: 11700 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 45000 1st Qu.:11.91
Median : 21800 Median : 0.00000 Median : 0.00000 Median : 0.00000 Median : 65000 Median :17.66
Mean : 29564 Mean : 0.02262 Mean : 0.03668 Mean : 0.04733 Mean : 75038 Mean :18.13
3rd Qu.: 37900 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 90000 3rd Qu.:23.94
Max. :9999999 Max. :16.00000 Max. :35.00000 Max. :32.00000 Max. :9500000 Max. :43.86
mths_since_delinq_cat mths_since_last_record_cat mths_since_rcnt_il_cat mths_since_last_major_derog_cat
Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
1st Qu.:3.000 1st Qu.:6.000 1st Qu.:6.000 1st Qu.:6.000
Median :6.000 Median :6.000 Median :6.000 Median :6.000
Mean :4.576 Mean :5.779 Mean :5.906 Mean :5.435
3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000
Max. :6.000 Max. :6.000 Max. :6.000 Max. :6.000
Learning Algorithms
# create indices for splitting (80% train, 20% test)
train_indices <- createDataPartition(lc_data$int_rate, p = 0.8, list = FALSE)
# create training and testing datasets
train_data <- lc_data[train_indices, ]
test_data <- lc_data[-train_indices, ]
#### Linear Regression ####
lm.fit <- lm(int_rate ~ ., data = train_data)
# make predictions on the training and testing data
lm.train_predictions <- predict(lm.fit, newdata = train_data)
lm.test_predictions <- predict(lm.fit, newdata = test_data)
# calculate Mean Squared Error (MSE) for training and testing
lm.train_mse <- mean((lm.train_predictions - train_data$int_rate)^2)
lm.test_mse <- mean((lm.test_predictions - test_data$int_rate)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
lm.train_rmse <- sqrt(lm.train_mse)
lm.test_rmse <- sqrt(lm.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
lm.train_mae <- mean(abs(lm.train_predictions - train_data$int_rate))
lm.test_mae <- mean(abs(lm.test_predictions - test_data$int_rate))
# calculate R-squared (R²) for training and testing
lm.train_r2 <- 1 - (sum((train_data$int_rate - lm.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
lm.test_r2 <- 1 - (sum((test_data$int_rate - lm.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# display the metrics
cat("Training MSE:", lm.train_mse, "\n")
Training MSE: 10.69206
cat("Testing MSE:", lm.test_mse, "\n")
Testing MSE: 11.07953
cat("Training RMSE:", lm.train_rmse, "\n")
Training RMSE: 3.269871
cat("Testing RMSE:", lm.test_rmse, "\n")
Testing RMSE: 3.328593
cat("Training MAE:", lm.train_mae, "\n")
Training MAE: 2.591219
cat("Testing MAE:", lm.test_mae, "\n")
Testing MAE: 2.591901
cat("Training R-squared (R²):", lm.train_r2, "\n")
Training R-squared (R²): 0.4432613
cat("Testing R-squared (R²):", lm.test_r2, "\n")
Testing R-squared (R²): 0.4228202
Lasso It standardizes data automatically
lasso.predictors_train <- model.matrix(int_rate ~ ., train_data)[,-1]
lasso.target_train <- train_data$int_rate
lasso.predictors_test <- model.matrix(int_rate ~ ., test_data)[,-1]
lasso.target_test <- test_data$int_rate
lasso.fit <- glmnet(lasso.predictors_train, lasso.target_train, alpha = 1)
plot(lasso.fit, label=TRUE)
# make predictions on the training and testing data
lasso.train_predictions <- predict(lasso.fit, newdata = train_data, newx = lasso.predictors_train)
lasso.test_predictions <- predict(lasso.fit, newdata = test_data, newx = lasso.predictors_train)
# calculate Mean Squared Error (MSE) for training and testing
lasso.train_mse <- mean((lasso.train_predictions - train_data$int_rate)^2)
lasso.test_mse <- mean((lasso.test_predictions - test_data$int_rate)^2)
Warning: longer object length is not a multiple of shorter object length
# calculate Root Mean Squared Error (RMSE) for training and testing
lasso.train_rmse <- sqrt(lasso.train_mse)
lasso.test_rmse <- sqrt(lasso.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
lasso.train_mae <- mean(abs(lasso.train_predictions - train_data$int_rate))
lasso.test_mae <- mean(abs(lasso.test_predictions - test_data$int_rate))
Warning: longer object length is not a multiple of shorter object length
# calculate R-squared (R²) for training and testing
lasso.train_r2 <- 1 - (sum((train_data$int_rate - lasso.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
lasso.test_r2 <- 1 - (sum((test_data$int_rate - lasso.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
Warning: longer object length is not a multiple of shorter object length
# display the metrics
cat("Training MSE:", lasso.train_mse, "\n")
Training MSE: 12.01177
cat("Testing MSE:", lasso.test_mse, "\n")
Testing MSE: 25.14051
cat("Training RMSE:", lasso.train_rmse, "\n")
Training RMSE: 3.4658
cat("Testing RMSE:", lasso.test_rmse, "\n")
Testing RMSE: 5.014031
cat("Training MAE:", lasso.train_mae, "\n")
Training MAE: 2.754045
cat("Testing MAE:", lasso.test_mae, "\n")
Testing MAE: 4.012612
cat("Training R-squared (R²):", lasso.train_r2, "\n")
Training R-squared (R²): -46.53467
cat("Testing R-squared (R²):", lasso.test_r2, "\n")
Testing R-squared (R²): -397.1465
Ridge It standardizes data automatically
ridge.predictors_train <- model.matrix(int_rate ~ ., train_data)[,-1]
ridge.target_train <- train_data$int_rate
ridge.predictors_test <- model.matrix(int_rate ~ ., test_data)[,-1]
ridge.target_test <- test_data$int_rate
ridge.fit <- glmnet(ridge.predictors_train, ridge.target_train, alpha = 0)
plot(ridge.fit, label=TRUE, xlab = "L2 Norm")
# make predictions on the training and testing data
ridge.train_predictions <- predict(ridge.fit, newdata = train_data, newx = ridge.predictors_train)
ridge.test_predictions <- predict(ridge.fit, newdata = test_data, newx = ridge.predictors_train)
# calculate Mean Squared Error (MSE) for training and testing
ridge.train_mse <- mean((ridge.train_predictions - train_data$int_rate)^2)
ridge.test_mse <- mean((ridge.test_predictions - test_data$int_rate)^2)
Warning: longer object length is not a multiple of shorter object length
# calculate Root Mean Squared Error (RMSE) for training and testing
ridge.train_rmse <- sqrt(ridge.train_mse)
ridge.test_rmse <- sqrt(ridge.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
ridge.train_mae <- mean(abs(ridge.train_predictions - train_data$int_rate))
ridge.test_mae <- mean(abs(ridge.test_predictions - test_data$int_rate))
Warning: longer object length is not a multiple of shorter object length
# calculate R-squared (R²) for training and testing
ridge.train_r2 <- 1 - (sum((train_data$int_rate - ridge.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
ridge.test_r2 <- 1 - (sum((test_data$int_rate - ridge.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
Warning: longer object length is not a multiple of shorter object length
# display the metrics
cat("Training MSE:", ridge.train_mse, "\n")
Training MSE: 15.24403
cat("Testing MSE:", ridge.test_mse, "\n")
Testing MSE: 21.3636
cat("Training RMSE:", ridge.train_rmse, "\n")
Training RMSE: 3.90436
cat("Testing RMSE:", ridge.test_rmse, "\n")
Testing RMSE: 4.622077
cat("Training MAE:", ridge.train_mae, "\n")
Training MAE: 3.102204
cat("Testing MAE:", ridge.test_mae, "\n")
Testing MAE: 3.703659
cat("Training R-squared (R²):", ridge.train_r2, "\n")
Training R-squared (R²): -78.3761
cat("Testing R-squared (R²):", ridge.test_r2, "\n")
Testing R-squared (R²): -444.1739
K fold using K=5:
# define the number of folds for cross-validation
num_folds <- 5
folds <- createFolds(train_data$int_rate, k = num_folds, list = TRUE)
K fold using K=5 and linear regression:
#### Linear Regresion applying Cross Validation with k=5 ####
# initialize lists to store models and their results
lm.k5.models <- list()
lm.k5.results <- data.frame()
# perform k-fold cross-validation
for(i in seq_along(folds)) {
# split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# fit the model on the training fold
lm.k5 <- lm(int_rate ~ ., data = train_data_fold)
lm.k5.models[[i]] <- lm.k5 # Store the model
# make predictions on the training and testing fold
lm.k5.train_predictions <- predict(lm.k5, newdata = train_data_fold)
lm.k5.test_predictions <- predict(lm.k5, newdata = test_data_fold)
# calculate metrics for training fold
lm.k5.train_mse <- mean((lm.k5.train_predictions - train_data_fold$int_rate)^2)
lm.k5.train_rmse <- sqrt(lm.k5.train_mse)
lm.k5.train_mae <- mean(abs(lm.k5.train_predictions - train_data_fold$int_rate))
lm.k5.train_r2 <- summary(lm.k5)$r.squared
# calculate metrics for testing fold
lm.k5.test_mse <- mean((lm.k5.test_predictions - test_data_fold$int_rate)^2)
lm.k5.test_rmse <- sqrt(lm.k5.test_mse)
lm.k5.test_mae <- mean(abs(lm.k5.test_predictions - test_data_fold$int_rate))
lm.k5.test_r2 <- 1 - (sum((test_data_fold$int_rate - lm.k5.test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
# store metrics in the results dataframe
lm.k5.results <- rbind(lm.k5.results, data.frame(
Fold = i,
Train_MSE = lm.k5.train_mse, Test_MSE = lm.k5.test_mse,
Train_RMSE = lm.k5.train_rmse, Test_RMSE = lm.k5.test_rmse,
Train_MAE = lm.k5.train_mae, Test_MAE = lm.k5.test_mae,
Train_R2 = lm.k5.train_r2, Test_R2 = lm.k5.test_r2
))
}
# display the models and their metrics
print(lm.k5.models)
[[1]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.910e+00 3.233e-05 3.920e+00
emp_length home_ownership verification_status
1.263e-02 2.509e-01 7.581e-01
purpose addr_state delinq_2yrs
3.386e-01 6.130e-05 3.605e-02
earliest_cr_line inq_last_6mths open_acc
1.871e-09 9.649e-01 6.637e-02
pub_rec revol_bal revol_util
3.463e-01 3.865e-06 4.248e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.603e-02 -1.014e+00 2.191e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.026e+00 2.246e-05 -1.206e-06
open_acc_6m open_il_6m open_il_12m
-1.330e-02 -1.596e-01 7.716e-01
open_il_24m total_bal_il il_util
4.741e-02 7.607e-07 9.710e-03
open_rv_12m open_rv_24m max_bal_bc
1.586e-01 7.933e-02 -3.460e-05
all_util total_rev_hi_lim inq_fi
-4.508e-03 -1.646e-05 6.036e-02
total_cu_tl inq_last_12m annual_inc_merged
-4.045e-02 7.753e-02 -3.377e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.160e-02 -2.022e-01 -1.924e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.467e-01 -1.427e-01
[[2]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.041e+00 2.416e-05 3.944e+00
emp_length home_ownership verification_status
1.658e-02 2.442e-01 7.451e-01
purpose addr_state delinq_2yrs
3.440e-01 -4.483e-04 3.113e-02
earliest_cr_line inq_last_6mths open_acc
1.998e-09 9.973e-01 4.845e-02
pub_rec revol_bal revol_util
3.922e-01 -6.678e-06 4.788e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.298e-02 -1.071e+00 3.099e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.257e+00 2.136e-05 -1.509e-06
open_acc_6m open_il_6m open_il_12m
1.282e-01 -1.558e-01 6.939e-01
open_il_24m total_bal_il il_util
3.900e-02 2.395e-06 3.730e-03
open_rv_12m open_rv_24m max_bal_bc
1.319e-01 6.035e-02 -7.830e-05
all_util total_rev_hi_lim inq_fi
1.620e-03 -3.147e-06 9.833e-02
total_cu_tl inq_last_12m annual_inc_merged
-7.565e-02 6.516e-02 -3.608e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.144e-02 -2.073e-01 -1.765e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.746e-01 -1.533e-01
[[3]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.706e+00 3.616e-05 3.867e+00
emp_length home_ownership verification_status
1.486e-02 2.624e-01 7.410e-01
purpose addr_state delinq_2yrs
3.365e-01 6.215e-04 4.298e-02
earliest_cr_line inq_last_6mths open_acc
1.890e-09 9.889e-01 6.379e-02
pub_rec revol_bal revol_util
4.020e-01 5.529e-06 4.188e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.451e-02 -1.025e+00 3.280e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.464e+00 3.626e-05 -1.005e-06
open_acc_6m open_il_6m open_il_12m
-6.804e-03 -1.613e-01 7.425e-01
open_il_24m total_bal_il il_util
6.193e-02 2.215e-06 5.888e-03
open_rv_12m open_rv_24m max_bal_bc
2.849e-01 4.946e-03 -4.102e-05
all_util total_rev_hi_lim inq_fi
1.527e-04 -1.706e-05 2.065e-03
total_cu_tl inq_last_12m annual_inc_merged
-2.524e-02 9.353e-02 -4.838e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.081e-02 -1.950e-01 -1.511e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.557e-01 -1.507e-01
[[4]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.893e+00 2.584e-05 3.910e+00
emp_length home_ownership verification_status
1.312e-02 2.583e-01 7.449e-01
purpose addr_state delinq_2yrs
3.440e-01 2.482e-05 4.644e-02
earliest_cr_line inq_last_6mths open_acc
1.989e-09 9.995e-01 4.512e-02
pub_rec revol_bal revol_util
4.346e-01 -3.946e-06 4.732e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.150e-02 -1.090e+00 3.695e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.287e+00 3.196e-05 -1.526e-06
open_acc_6m open_il_6m open_il_12m
-6.852e-02 -1.189e-01 8.625e-01
open_il_24m total_bal_il il_util
2.418e-02 1.271e-07 4.949e-03
open_rv_12m open_rv_24m max_bal_bc
2.133e-01 6.556e-02 -6.542e-05
all_util total_rev_hi_lim inq_fi
9.265e-04 -3.429e-06 6.894e-02
total_cu_tl inq_last_12m annual_inc_merged
-6.816e-02 6.176e-02 -4.018e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.046e-02 -2.031e-01 -1.855e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.063e-01 -1.426e-01
[[5]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.990e+00 3.206e-05 3.892e+00
emp_length home_ownership verification_status
1.746e-02 2.751e-01 7.288e-01
purpose addr_state delinq_2yrs
3.330e-01 6.527e-04 2.890e-02
earliest_cr_line inq_last_6mths open_acc
1.894e-09 9.916e-01 6.403e-02
pub_rec revol_bal revol_util
4.223e-01 7.105e-06 4.250e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.643e-02 -9.932e-01 2.520e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.367e+00 2.487e-05 -1.039e-06
open_acc_6m open_il_6m open_il_12m
9.287e-02 -1.552e-01 6.460e-01
open_il_24m total_bal_il il_util
4.842e-02 3.241e-06 5.126e-03
open_rv_12m open_rv_24m max_bal_bc
1.508e-01 8.182e-02 -6.169e-05
all_util total_rev_hi_lim inq_fi
-6.585e-04 -1.709e-05 -3.103e-02
total_cu_tl inq_last_12m annual_inc_merged
-5.278e-02 9.582e-02 -3.462e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.261e-02 -2.006e-01 -1.559e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.809e-01 -1.417e-01
print(lm.k5.results)
plot_metric <- function(results_long, metric) {
# adjust the variable names based on the metric
variables <- if (metric == "OOB") {
"OOB_Error"
} else {
c(paste0('Train_', metric), paste0('Test_', metric))
}
title <- if (metric == "OOB") {
paste0(metric, ' per Fold')
} else {
paste0('Train vs Test ', metric, ' per Fold')
}
ggplot(results_long[results_long$variable %in% variables, ],
aes(x = Fold, y = value, color = variable)) +
geom_line() +
geom_point() +
theme_minimal() +
labs(title = title,
x = 'Fold',
y = metric)
}
# reshape data for plotting
lm.k5.results_long <- melt(lm.k5.results, id.vars = 'Fold')
# plot for each metric
p1 <- plot_metric(lm.k5.results_long, 'MSE')
p2 <- plot_metric(lm.k5.results_long, 'RMSE')
p3 <- plot_metric(lm.k5.results_long, 'MAE')
p4 <- plot_metric(lm.k5.results_long, 'R2')
# arrange the plots in a 2x2 grid
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
plot(p1)
plot(p2)
plot(p3)
plot(p4)
K fold using K=5 and Random Forest:
#### Random Forest applying Cross Validation with k=5 ####
# initialize lists to store models and their results
rf.k5.models <- list()
rf.k5.results <- data.frame()
# perform k-fold cross-validation
for(i in seq_along(folds)) {
# split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# fit the model on the training fold
rf.k5 <- ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
rf.k5.models[[i]] <- rf.k5 # Store the model
# make predictions on the training and testing fold
rf.k5.train_predictions <- predict(rf.k5, data = train_data_fold)$predictions
rf.k5.test_predictions <- predict(rf.k5, data = test_data_fold)$predictions
# calculate metrics for training fold
rf.k5.train_mse <- mean((rf.k5.train_predictions - train_data_fold$int_rate)^2)
rf.k5.train_rmse <- sqrt(rf.k5.train_mse)
rf.k5.train_mae <- mean(abs(rf.k5.train_predictions - train_data_fold$int_rate))
rf.k5.oob_error <- rf.k5$prediction.error
# calculate metrics for testing fold
rf.k5.test_mse <- mean((rf.k5.test_predictions - test_data_fold$int_rate)^2)
rf.k5.test_rmse <- sqrt(rf.k5.test_mse)
rf.k5.test_mae <- mean(abs(rf.k5.test_predictions - test_data_fold$int_rate))
rf.k5.test_r2 <- 1 - (sum((test_data_fold$int_rate - rf.k5.test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
# store metrics in the results dataframe
rf.k5.results <- rbind(rf.k5.results, data.frame(
Fold = i,
Train_MSE = rf.k5.train_mse, Test_MSE = rf.k5.test_mse,
Train_RMSE = rf.k5.train_rmse, Test_RMSE = rf.k5.test_rmse,
Train_MAE = rf.k5.train_mae, Test_MAE = rf.k5.test_mae,
OOB_Error = rf.k5.oob_error
))
}
Growing trees.. Progress: 16%. Estimated remaining time: 2 minutes, 47 seconds.
Growing trees.. Progress: 32%. Estimated remaining time: 2 minutes, 10 seconds.
Growing trees.. Progress: 48%. Estimated remaining time: 1 minute, 39 seconds.
Growing trees.. Progress: 64%. Estimated remaining time: 1 minute, 9 seconds.
Growing trees.. Progress: 80%. Estimated remaining time: 39 seconds.
Growing trees.. Progress: 95%. Estimated remaining time: 9 seconds.
Growing trees.. Progress: 16%. Estimated remaining time: 2 minutes, 42 seconds.
Growing trees.. Progress: 32%. Estimated remaining time: 2 minutes, 12 seconds.
Growing trees.. Progress: 50%. Estimated remaining time: 1 minute, 35 seconds.
Growing trees.. Progress: 66%. Estimated remaining time: 1 minute, 5 seconds.
Growing trees.. Progress: 83%. Estimated remaining time: 32 seconds.
Growing trees.. Progress: 99%. Estimated remaining time: 1 seconds.
Growing trees.. Progress: 16%. Estimated remaining time: 2 minutes, 45 seconds.
Growing trees.. Progress: 32%. Estimated remaining time: 2 minutes, 10 seconds.
Growing trees.. Progress: 48%. Estimated remaining time: 1 minute, 41 seconds.
Growing trees.. Progress: 64%. Estimated remaining time: 1 minute, 9 seconds.
Growing trees.. Progress: 80%. Estimated remaining time: 38 seconds.
Growing trees.. Progress: 97%. Estimated remaining time: 6 seconds.
Growing trees.. Progress: 15%. Estimated remaining time: 2 minutes, 58 seconds.
Growing trees.. Progress: 31%. Estimated remaining time: 2 minutes, 18 seconds.
Growing trees.. Progress: 47%. Estimated remaining time: 1 minute, 45 seconds.
Growing trees.. Progress: 63%. Estimated remaining time: 1 minute, 12 seconds.
Growing trees.. Progress: 79%. Estimated remaining time: 40 seconds.
Growing trees.. Progress: 95%. Estimated remaining time: 9 seconds.
Growing trees.. Progress: 16%. Estimated remaining time: 2 minutes, 45 seconds.
Growing trees.. Progress: 33%. Estimated remaining time: 2 minutes, 12 seconds.
Growing trees.. Progress: 48%. Estimated remaining time: 1 minute, 42 seconds.
Growing trees.. Progress: 64%. Estimated remaining time: 1 minute, 12 seconds.
Growing trees.. Progress: 80%. Estimated remaining time: 38 seconds.
Growing trees.. Progress: 96%. Estimated remaining time: 7 seconds.
# display the models and their metrics
print(rf.k5.models)
[[1]]
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.751032
R squared (OOB): 0.5443319
[[2]]
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.746286
R squared (OOB): 0.544579
[[3]]
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.749652
R squared (OOB): 0.5444038
[[4]]
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.746698
R squared (OOB): 0.5445576
[[5]]
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.747217
R squared (OOB): 0.5445306
print(rf.k5.results)
# reshape data for plotting
rf.k5.results_long <- melt(rf.k5.results, id.vars = 'Fold')
# plot for each metric
p1 <- plot_metric(rf.k5.results_long, 'MSE')
p2 <- plot_metric(rf.k5.results_long, 'RMSE')
p3 <- plot_metric(rf.k5.results_long, 'MAE')
p4 <- plot_metric(rf.k5.results_long, 'OOB')
# arrange the plots in a 2x2 grid
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
plot(p1)
plot(p2)
plot(p3)
plot(p4)
K fold using K=5 and Boosting:
#### Boosting applying Cross Validation with k=5 ####
# initialize lists to store models and their results
xgb.k5.models <- list()
xgb.k5.results <- data.frame()
# perform k-fold cross-validation
for(i in seq_along(folds)) {
# split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# prepare data for xgboost
xgb.y_train_fold <- train_data_fold$int_rate
xgb.X_train_fold <- as.matrix(train_data_fold[, -which(names(train_data_fold) == 'int_rate')])
xgb.y_test_fold <- test_data_fold$int_rate
xgb.X_test_fold <- as.matrix(test_data_fold[, -which(names(test_data_fold) == 'int_rate')])
# fit the xgboost model on the training fold
xgb.k5 <- xgboost(
data = xgb.X_train_fold,
label = xgb.y_train_fold,
nrounds = 100,
verbose = 0
)
xgb.k5.models[[i]] <- xgb.k5 # store the model
# make predictions on the training fold
xgb.k5.train_predictions <- predict(xgb.k5, newdata = xgb.X_train_fold)
# make predictions on the testing fold
xgb.k5.test_predictions <- predict(xgb.k5, newdata = xgb.X_test_fold)
# calculate metrics for training fold
xgb.k5.train_mse <- mean((xgb.k5.train_predictions - train_data_fold$int_rate)^2)
xgb.k5.train_rmse <- sqrt(xgb.k5.train_mse)
xgb.k5.train_mae <- mean(abs(xgb.k5.train_predictions - train_data_fold$int_rate))
xgb.k5.train_r2 <- 1 - (sum((xgb.y_train_fold - xgb.k5.train_predictions)^2) / sum((xgb.y_train_fold - mean(xgb.y_train_fold))^2))
# calculate metrics for testing fold
xgb.k5.test_mse <- mean((xgb.k5.test_predictions - xgb.y_test_fold)^2)
xgb.k5.test_rmse <- sqrt(xgb.k5.test_mse)
xgb.k5.test_mae <- mean(abs(xgb.k5.test_predictions - xgb.y_test_fold))
xgb.k5.test_r2 <- 1 - (sum((xgb.y_test_fold - xgb.k5.test_predictions)^2) / sum((xgb.y_test_fold - mean(xgb.y_test_fold))^2))
# store metrics in the results dataframe
xgb.k5.results <- rbind(xgb.k5.results, data.frame(
Fold = i,
Train_MSE = xgb.k5.train_mse, Test_MSE = xgb.k5.test_mse,
Train_RMSE = xgb.k5.train_rmse, Test_RMSE = xgb.k5.test_rmse,
Train_MAE = xgb.k5.train_mae, Test_MAE = xgb.k5.test_mae,
Train_R2 = xgb.k5.train_r2, Test_R2 = xgb.k5.test_r2
))
}
# display the models and their metrics
print(xgb.k5.models)
[[1]]
##### xgb.Booster
raw: 450.2 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[2]]
##### xgb.Booster
raw: 442.2 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[3]]
##### xgb.Booster
raw: 443.5 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[4]]
##### xgb.Booster
raw: 447.1 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[5]]
##### xgb.Booster
raw: 451 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
print(xgb.k5.results)
# reshape data for plotting
xgb.k5.results_long <- melt(xgb.k5.results, id.vars = 'Fold')
# plot for each metric
p1 <- plot_metric(xgb.k5.results_long, 'MSE')
p2 <- plot_metric(xgb.k5.results_long, 'RMSE')
p3 <- plot_metric(xgb.k5.results_long, 'MAE')
p4 <- plot_metric(xgb.k5.results_long, 'R2')
# arrange the plots in a 2x2 grid
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
plot(p1)
plot(p2)
plot(p3)
plot(p4)
K fold using K=10:
# define the number of folds for cross-validation
num_folds <- 10
folds <- createFolds(train_data$int_rate, k = num_folds, list = TRUE)
K fold using K=10 and linear regression:
#### Linear Regresion applying Cross Validation with k=10 ####
# initialize lists to store models and their results
lm.k10.models <- list()
lm.k10.results <- data.frame()
# perform k-fold cross-validation
for(i in seq_along(folds)) {
# split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# fit the model on the training fold
lm.k10 <- lm(int_rate ~ ., data = train_data_fold)
lm.k10.models[[i]] <- lm.k10 # Store the model
# make predictions on the training and testing fold
lm.k10.train_predictions <- predict(lm.k10, newdata = train_data_fold)
lm.k10.test_predictions <- predict(lm.k10, newdata = test_data_fold)
# calculate metrics for training fold
lm.k10.train_mse <- mean((lm.k10.train_predictions - train_data_fold$int_rate)^2)
lm.k10.train_rmse <- sqrt(lm.k10.train_mse)
lm.k10.train_mae <- mean(abs(lm.k10.train_predictions - train_data_fold$int_rate))
lm.k10.train_r2 <- summary(lm.k10)$r.squared
# calculate metrics for testing fold
lm.k10.test_mse <- mean((lm.k10.test_predictions - test_data_fold$int_rate)^2)
lm.k10.test_rmse <- sqrt(lm.k10.test_mse)
lm.k10.test_mae <- mean(abs(lm.k10.test_predictions - test_data_fold$int_rate))
lm.k10.test_r2 <- 1 - (sum((test_data_fold$int_rate - lm.k10.test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
# store metrics in the results dataframe
lm.k10.results <- rbind(lm.k10.results, data.frame(
Fold = i,
Train_MSE = lm.k10.train_mse, Test_MSE = lm.k10.test_mse,
Train_RMSE = lm.k10.train_rmse, Test_RMSE = lm.k10.test_rmse,
Train_MAE = lm.k10.train_mae, Test_MAE = lm.k10.test_mae,
Train_R2 = lm.k10.train_r2, Test_R2 = lm.k10.test_r2
))
}
# display the models and their metrics
print(lm.k10.models)
[[1]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.837e+00 2.761e-05 3.914e+00
emp_length home_ownership verification_status
1.407e-02 2.499e-01 7.342e-01
purpose addr_state delinq_2yrs
3.385e-01 1.386e-04 3.439e-02
earliest_cr_line inq_last_6mths open_acc
1.875e-09 9.893e-01 6.491e-02
pub_rec revol_bal revol_util
4.515e-01 8.460e-06 4.138e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.711e-02 -1.047e+00 2.295e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.391e+00 3.117e-05 -1.433e-06
open_acc_6m open_il_6m open_il_12m
-1.691e-02 -1.541e-01 1.003e+00
open_il_24m total_bal_il il_util
-1.838e-01 2.623e-06 1.102e-02
open_rv_12m open_rv_24m max_bal_bc
2.018e-01 4.167e-02 1.694e-06
all_util total_rev_hi_lim inq_fi
-8.827e-03 -1.778e-05 7.364e-02
total_cu_tl inq_last_12m annual_inc_merged
-2.619e-02 9.273e-02 -2.354e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.175e-02 -2.058e-01 -1.284e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.155e-01 -1.363e-01
[[2]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.392e+00 3.706e-05 3.841e+00
emp_length home_ownership verification_status
1.703e-02 2.717e-01 7.160e-01
purpose addr_state delinq_2yrs
3.370e-01 -5.944e-05 3.843e-02
earliest_cr_line inq_last_6mths open_acc
1.881e-09 1.000e+00 6.417e-02
pub_rec revol_bal revol_util
3.828e-01 6.538e-06 4.193e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.469e-02 -9.695e-01 2.127e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.530e+00 1.858e-05 -6.860e-07
open_acc_6m open_il_6m open_il_12m
5.075e-02 -1.453e-01 1.046e+00
open_il_24m total_bal_il il_util
-1.060e-01 1.655e-06 5.956e-03
open_rv_12m open_rv_24m max_bal_bc
2.677e-01 5.487e-02 -5.448e-05
all_util total_rev_hi_lim inq_fi
-5.830e-03 -1.835e-05 1.787e-01
total_cu_tl inq_last_12m annual_inc_merged
-5.512e-02 4.549e-02 -6.257e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
4.889e-02 -1.998e-01 -1.771e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.853e-01 -1.501e-01
[[3]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.022e+00 3.483e-05 3.833e+00
emp_length home_ownership verification_status
1.891e-02 2.816e-01 7.334e-01
purpose addr_state delinq_2yrs
3.325e-01 3.149e-04 5.353e-02
earliest_cr_line inq_last_6mths open_acc
1.881e-09 9.790e-01 6.751e-02
pub_rec revol_bal revol_util
3.643e-01 5.100e-06 4.308e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.489e-02 -9.994e-01 9.544e-02
acc_now_delinq tot_coll_amt tot_cur_bal
7.195e-01 3.676e-05 -1.399e-06
open_acc_6m open_il_6m open_il_12m
8.692e-02 -1.618e-01 5.872e-01
open_il_24m total_bal_il il_util
8.364e-02 2.175e-07 3.842e-03
open_rv_12m open_rv_24m max_bal_bc
8.637e-02 7.590e-02 -2.945e-05
all_util total_rev_hi_lim inq_fi
-1.163e-04 -1.710e-05 -4.120e-02
total_cu_tl inq_last_12m annual_inc_merged
-5.019e-02 8.224e-02 -2.299e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.562e-02 -1.904e-01 -1.829e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.757e-01 -1.433e-01
[[4]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.504e+00 3.187e-05 3.908e+00
emp_length home_ownership verification_status
1.735e-02 2.586e-01 7.342e-01
purpose addr_state delinq_2yrs
3.435e-01 1.434e-03 3.207e-03
earliest_cr_line inq_last_6mths open_acc
1.850e-09 9.701e-01 6.578e-02
pub_rec revol_bal revol_util
4.056e-01 3.981e-06 4.469e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.554e-02 -9.507e-01 3.245e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.578e+00 2.964e-05 -1.206e-06
open_acc_6m open_il_6m open_il_12m
-4.212e-02 -1.617e-01 8.188e-01
open_il_24m total_bal_il il_util
1.138e-01 4.928e-06 6.491e-03
open_rv_12m open_rv_24m max_bal_bc
9.391e-02 7.342e-02 -3.985e-05
all_util total_rev_hi_lim inq_fi
-3.838e-03 -1.592e-05 -1.052e-01
total_cu_tl inq_last_12m annual_inc_merged
-2.561e-02 1.874e-01 -3.866e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
4.879e-02 -1.971e-01 -1.447e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.533e-01 -1.591e-01
[[5]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.209e+00 3.012e-05 3.880e+00
emp_length home_ownership verification_status
1.219e-02 2.479e-01 7.448e-01
purpose addr_state delinq_2yrs
3.274e-01 2.441e-04 4.065e-02
earliest_cr_line inq_last_6mths open_acc
1.873e-09 1.008e+00 5.760e-02
pub_rec revol_bal revol_util
3.269e-01 1.939e-06 4.323e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.393e-02 -1.016e+00 3.320e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.187e+00 2.533e-05 -1.187e-06
open_acc_6m open_il_6m open_il_12m
-5.177e-02 -1.412e-01 8.744e-01
open_il_24m total_bal_il il_util
5.048e-02 5.570e-08 2.402e-03
open_rv_12m open_rv_24m max_bal_bc
1.861e-01 1.138e-01 -6.366e-05
all_util total_rev_hi_lim inq_fi
1.230e-03 -1.563e-05 8.822e-02
total_cu_tl inq_last_12m annual_inc_merged
-7.063e-02 5.952e-02 -3.328e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.296e-02 -2.057e-01 -1.924e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.913e-01 -1.167e-01
[[6]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.168e+00 3.915e-05 3.871e+00
emp_length home_ownership verification_status
1.352e-02 2.633e-01 7.751e-01
purpose addr_state delinq_2yrs
3.390e-01 1.749e-03 1.910e-02
earliest_cr_line inq_last_6mths open_acc
1.832e-09 9.636e-01 6.742e-02
pub_rec revol_bal revol_util
4.285e-01 3.395e-06 4.243e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.525e-02 -9.923e-01 5.245e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.433e+00 3.226e-05 -7.911e-07
open_acc_6m open_il_6m open_il_12m
-8.548e-02 -1.390e-01 7.381e-01
open_il_24m total_bal_il il_util
1.076e-01 2.062e-06 5.865e-03
open_rv_12m open_rv_24m max_bal_bc
2.432e-01 7.391e-02 -5.362e-05
all_util total_rev_hi_lim inq_fi
3.292e-03 -1.637e-05 -3.937e-03
total_cu_tl inq_last_12m annual_inc_merged
-3.718e-02 9.189e-02 -6.204e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
4.815e-02 -2.050e-01 -1.280e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
4.212e-01 -1.461e-01
[[7]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.285e+00 2.186e-05 3.935e+00
emp_length home_ownership verification_status
7.481e-03 2.543e-01 7.479e-01
purpose addr_state delinq_2yrs
3.419e-01 -1.227e-03 4.564e-02
earliest_cr_line inq_last_6mths open_acc
2.064e-09 9.941e-01 4.423e-02
pub_rec revol_bal revol_util
4.754e-01 -4.976e-06 4.734e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.345e-02 -1.095e+00 2.513e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.114e+00 1.688e-05 -1.262e-06
open_acc_6m open_il_6m open_il_12m
1.465e-01 -1.145e-01 4.180e-01
open_il_24m total_bal_il il_util
1.079e-01 3.507e-06 1.597e-03
open_rv_12m open_rv_24m max_bal_bc
1.729e-01 5.808e-02 -6.954e-05
all_util total_rev_hi_lim inq_fi
2.577e-04 -8.575e-07 2.366e-02
total_cu_tl inq_last_12m annual_inc_merged
-2.773e-02 3.311e-02 -4.980e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
4.976e-02 -2.165e-01 -1.862e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.814e-01 -1.584e-01
[[8]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.886e+00 2.951e-05 3.939e+00
emp_length home_ownership verification_status
1.907e-02 2.413e-01 7.281e-01
purpose addr_state delinq_2yrs
3.358e-01 -3.930e-04 3.378e-02
earliest_cr_line inq_last_6mths open_acc
1.835e-09 9.790e-01 6.102e-02
pub_rec revol_bal revol_util
5.061e-01 4.566e-06 4.316e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.194e-02 -1.004e+00 4.002e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.729e+00 3.088e-05 -1.232e-06
open_acc_6m open_il_6m open_il_12m
8.316e-02 -1.991e-01 7.761e-01
open_il_24m total_bal_il il_util
3.994e-02 3.296e-06 5.505e-03
open_rv_12m open_rv_24m max_bal_bc
2.273e-01 1.900e-05 -6.886e-05
all_util total_rev_hi_lim inq_fi
1.625e-03 -1.555e-05 1.082e-01
total_cu_tl inq_last_12m annual_inc_merged
-1.459e-01 6.960e-02 -3.340e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.213e-02 -1.958e-01 -1.031e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
2.445e-01 -1.429e-01
[[9]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
2.159e+00 3.265e-05 3.967e+00
emp_length home_ownership verification_status
1.195e-02 2.972e-01 7.602e-01
purpose addr_state delinq_2yrs
3.471e-01 6.885e-04 4.951e-02
earliest_cr_line inq_last_6mths open_acc
1.980e-09 1.003e+00 4.107e-02
pub_rec revol_bal revol_util
4.402e-01 -3.742e-06 4.724e-02
total_acc initial_list_status collections_12_mths_ex_med
-2.991e-02 -1.160e+00 2.061e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.381e+00 2.093e-05 -8.329e-07
open_acc_6m open_il_6m open_il_12m
1.517e-01 -1.813e-01 4.031e-01
open_il_24m total_bal_il il_util
1.897e-01 2.073e-06 9.850e-03
open_rv_12m open_rv_24m max_bal_bc
8.659e-02 5.072e-02 -1.021e-04
all_util total_rev_hi_lim inq_fi
1.806e-03 -1.832e-06 -2.228e-02
total_cu_tl inq_last_12m annual_inc_merged
-4.495e-02 1.021e-01 -8.067e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
4.395e-02 -1.989e-01 -2.025e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.087e-01 -1.601e-01
[[10]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt term
1.888e+00 3.751e-05 3.863e+00
emp_length home_ownership verification_status
1.638e-02 2.690e-01 7.461e-01
purpose addr_state delinq_2yrs
3.473e-01 -5.930e-04 4.231e-02
earliest_cr_line inq_last_6mths open_acc
1.968e-09 9.909e-01 6.522e-02
pub_rec revol_bal revol_util
2.888e-01 4.557e-06 4.309e-02
total_acc initial_list_status collections_12_mths_ex_med
-3.584e-02 -1.048e+00 4.556e-01
acc_now_delinq tot_coll_amt tot_cur_bal
1.046e+00 2.601e-05 -1.067e-06
open_acc_6m open_il_6m open_il_12m
-6.287e-02 -1.336e-01 7.843e-01
open_il_24m total_bal_il il_util
6.702e-02 -3.403e-06 6.013e-03
open_rv_12m open_rv_24m max_bal_bc
3.101e-01 4.605e-02 -6.596e-05
all_util total_rev_hi_lim inq_fi
2.231e-03 -1.673e-05 1.676e-01
total_cu_tl inq_last_12m annual_inc_merged
-4.114e-02 1.939e-02 -3.840e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.378e-02 -1.957e-01 -2.012e-01
mths_since_rcnt_il_cat mths_since_last_major_derog_cat
3.257e-01 -1.401e-01
print(lm.k10.results)
plot_metric <- function(results_long, metric) {
# adjust the variable names based on the metric
variables <- if (metric == "OOB") {
"OOB_Error"
} else {
c(paste0('Train_', metric), paste0('Test_', metric))
}
title <- if (metric == "OOB") {
paste0(metric, ' per Fold')
} else {
paste0('Train vs Test ', metric, ' per Fold')
}
ggplot(results_long[results_long$variable %in% variables, ],
aes(x = Fold, y = value, color = variable)) +
geom_line() +
geom_point() +
theme_minimal() +
labs(title = title,
x = 'Fold',
y = metric)
}
# reshape data for plotting
lm.k10.results_long <- melt(lm.k10.results, id.vars = 'Fold')
# plot for each metric
p1 <- plot_metric(lm.k10.results_long, 'MSE')
p2 <- plot_metric(lm.k10.results_long, 'RMSE')
p3 <- plot_metric(lm.k10.results_long, 'MAE')
p4 <- plot_metric(lm.k10.results_long, 'R2')
# arrange the plots in a 2x2 grid
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
plot(p1)
plot(p2)
plot(p3)
plot(p4)
K fold using K=10 and Random Forest:
# #### Random Forest applying Cross Validation with k=10 ####
#
# # initialize lists to store models and their results
# rf.k10.models <- list()
# rf.k10.results <- data.frame()
#
# # perform k-fold cross-validation
# for(i in seq_along(folds)) {
# # split the data into training and testing for the current fold
# train_indices <- folds[[i]]
# test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
#
# train_data_fold <- train_data[train_indices, ]
# test_data_fold <- train_data[test_indices, ]
#
# # fit the model on the training fold
# rf.k10 <- ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
# rf.k10.models[[i]] <- rf.k10 # Store the model
#
# # make predictions on the training and testing fold
# rf.k10.train_predictions <- predict(rf.k10, data = train_data_fold)$predictions
# rf.k10.test_predictions <- predict(rf.k10, data = test_data_fold)$predictions
#
# # calculate metrics for training fold
# rf.k10.train_mse <- mean((rf.k10.train_predictions - train_data_fold$int_rate)^2)
# rf.k10.train_rmse <- sqrt(rf.k10.train_mse)
# rf.k10.train_mae <- mean(abs(rf.k10.train_predictions - train_data_fold$int_rate))
# rf.k10.oob_error <- rf.k10$prediction.error
#
# # calculate metrics for testing fold
# rf.k10.test_mse <- mean((rf.k10.test_predictions - test_data_fold$int_rate)^2)
# rf.k10.test_rmse <- sqrt(rf.k10.test_mse)
# rf.k10.test_mae <- mean(abs(rf.k10.test_predictions - test_data_fold$int_rate))
# rf.k10.test_r2 <- 1 - (sum((test_data_fold$int_rate - rf.k10.test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
#
# # store metrics in the results dataframe
# rf.k10.results <- rbind(rf.k10.results, data.frame(
# Fold = i,
# Train_MSE = rf.k10.train_mse, Test_MSE = rf.k10.test_mse,
# Train_RMSE = rf.k10.train_rmse, Test_RMSE = rf.k10.test_rmse,
# Train_MAE = rf.k10.train_mae, Test_MAE = rf.k10.test_mae,
# OOB_Error = rf.k10.oob_error
# ))
# }
#
# # display the models and their metrics
# print(rf.k10.models)
# print(rf.k10.results)
# reshape data for plotting
# rf.k10.results_long <- melt(rf.k10.results, id.vars = 'Fold')
#
# # plot for each metric
# p1 <- plot_metric(rf.k10.results_long, 'MSE')
# p2 <- plot_metric(rf.k10.results_long, 'RMSE')
# p3 <- plot_metric(rf.k10.results_long, 'MAE')
# p4 <- plot_metric(rf.k10.results_long, 'OOB')
#
# # arrange the plots in a 2x2 grid
# grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
#
# plot(p1)
# plot(p2)
# plot(p3)
# plot(p4)
K fold using K=10 and Boosting:
#### Boosting applying Cross Validation with k=10 ####
# initialize lists to store models and their results
xgb.k10.models <- list()
xgb.k10.results <- data.frame()
# perform k-fold cross-validation
for(i in seq_along(folds)) {
# split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# prepare data for xgboost
xgb.y_train_fold <- train_data_fold$int_rate
xgb.X_train_fold <- as.matrix(train_data_fold[, -which(names(train_data_fold) == 'int_rate')])
xgb.y_test_fold <- test_data_fold$int_rate
xgb.X_test_fold <- as.matrix(test_data_fold[, -which(names(test_data_fold) == 'int_rate')])
# fit the xgboost model on the training fold
xgb.k10 <- xgboost(
data = xgb.X_train_fold,
label = xgb.y_train_fold,
nrounds = 100,
verbose = 0
)
xgb.k10.models[[i]] <- xgb.k10 # store the model
# make predictions on the training fold
xgb.k10.train_predictions <- predict(xgb.k10, newdata = xgb.X_train_fold)
# make predictions on the testing fold
xgb.k10.test_predictions <- predict(xgb.k10, newdata = xgb.X_test_fold)
# calculate metrics for training fold
xgb.k10.train_mse <- mean((xgb.k10.train_predictions - train_data_fold$int_rate)^2)
xgb.k10.train_rmse <- sqrt(xgb.k10.train_mse)
xgb.k10.train_mae <- mean(abs(xgb.k10.train_predictions - train_data_fold$int_rate))
xgb.k10.train_r2 <- 1 - (sum((xgb.y_train_fold - xgb.k10.train_predictions)^2) / sum((xgb.y_train_fold - mean(xgb.y_train_fold))^2))
# calculate metrics for testing fold
xgb.k10.test_mse <- mean((xgb.k10.test_predictions - xgb.y_test_fold)^2)
xgb.k10.test_rmse <- sqrt(xgb.k10.test_mse)
xgb.k10.test_mae <- mean(abs(xgb.k10.test_predictions - xgb.y_test_fold))
xgb.k10.test_r2 <- 1 - (sum((xgb.y_test_fold - xgb.k10.test_predictions)^2) / sum((xgb.y_test_fold - mean(xgb.y_test_fold))^2))
# store metrics in the results dataframe
xgb.k10.results <- rbind(xgb.k10.results, data.frame(
Fold = i,
Train_MSE = xgb.k10.train_mse, Test_MSE = xgb.k10.test_mse,
Train_RMSE = xgb.k10.train_rmse, Test_RMSE = xgb.k10.test_rmse,
Train_MAE = xgb.k10.train_mae, Test_MAE = xgb.k10.test_mae,
Train_R2 = xgb.k10.train_r2, Test_R2 = xgb.k10.test_r2
))
}
# display the models and their metrics
print(xgb.k10.models)
[[1]]
##### xgb.Booster
raw: 432.1 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[2]]
##### xgb.Booster
raw: 432.4 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[3]]
##### xgb.Booster
raw: 433.4 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[4]]
##### xgb.Booster
raw: 432.1 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[5]]
##### xgb.Booster
raw: 438.5 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[6]]
##### xgb.Booster
raw: 433.8 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[7]]
##### xgb.Booster
raw: 438.8 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[8]]
##### xgb.Booster
raw: 438.9 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[9]]
##### xgb.Booster
raw: 441.5 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
[[10]]
##### xgb.Booster
raw: 437.6 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks)
params (as set within xgb.train):
validate_parameters = "TRUE"
xgb.attributes:
niter
callbacks:
cb.evaluation.log()
# of features: 40
niter: 100
nfeatures : 40
evaluation_log:
print(xgb.k10.results)
# reshape data for plotting
xgb.k10.results_long <- melt(xgb.k10.results, id.vars = 'Fold')
# plot for each metric
p1 <- plot_metric(xgb.k10.results_long, 'MSE')
p2 <- plot_metric(xgb.k10.results_long, 'RMSE')
p3 <- plot_metric(xgb.k10.results_long, 'MAE')
p4 <- plot_metric(xgb.k10.results_long, 'R2')
# arrange the plots in a 2x2 grid
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
plot(p1)
plot(p2)
plot(p3)
plot(p4)
Decision Trees
#### Decision Trees ####
# error in tree: "factor predictors must have at most 32 levels" is thrown
# basically, it becomes computationally expensive to create so many splits in your data, since you are selecting the best split out of all 2^32 (approx) possible splits
# fit a decision tree model on the training data
#tm <- tree(int_rate ~ ., data = train_data)
# make predictions on the training and testing data
#tm.train_predictions <- predict(tm, newdata = train_data)
#tm.test_predictions <- predict(tm, newdata = test_data)
# calculate Mean Squared Error (MSE) for training and testing
#tm.train_mse <- mean((tm.train_predictions - train_data$int_rate)^2)
#tm.test_mse <- mean((tm.test_predictions - test_data$int_rate)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
#tm.train_rmse <- sqrt(tm.train_mse)
#tm.test_rmse <- sqrt(tm.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
#tm.train_mae <- mean(abs(tm.train_predictions - train_data$int_rate))
#tm.test_mae <- mean(abs(tm.test_predictions - test_data$int_rate))
# calculate R-squared (R²) for training and testing
#tm.train_r2 <- 1 - (sum((train_data$int_rate - tm.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
#tm.test_r2 <- 1 - (sum((test_data$int_rate - tm.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# display the metrics
#cat("Training MSE:", tm.train_mse, "\n")
#cat("Testing MSE:", tm.test_mse, "\n")
#cat("Training RMSE:", tm.train_rmse, "\n")
#cat("Testing RMSE:", tm.test_rmse, "\n")
#cat("Training MAE:", tm.train_mae, "\n")
#cat("Testing MAE:", tm.test_mae, "\n")
#cat("Training R-squared (R²):", tm.train_r2, "\n")
#cat("Testing R-squared (R²):", tm.test_r2, "\n")
Random Forest
#### Random Forest ####
# train a Random Forest model
rf <- ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
Growing trees.. Progress: 16%. Estimated remaining time: 2 minutes, 42 seconds.
Growing trees.. Progress: 32%. Estimated remaining time: 2 minutes, 12 seconds.
Growing trees.. Progress: 49%. Estimated remaining time: 1 minute, 38 seconds.
Growing trees.. Progress: 65%. Estimated remaining time: 1 minute, 7 seconds.
Growing trees.. Progress: 81%. Estimated remaining time: 35 seconds.
Growing trees.. Progress: 98%. Estimated remaining time: 4 seconds.
# print the model summary
print("Random Forest Model Summary:")
[1] "Random Forest Model Summary:"
print(rf)
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.747259
R squared (OOB): 0.5445284
# make predictions on the training and testing data
rf.train_predictions <- predict(rf, data = train_data)
rf.test_predictions <- predict(rf, data = test_data)
# calculate Mean Squared Error (MSE) for training and testing
rf.train_mse <- mean((rf.train_predictions$predictions - train_data$int_rate)^2)
rf.test_mse <- mean((rf.test_predictions$predictions - test_data$int_rate)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
rf.train_rmse <- sqrt(rf.train_mse)
rf.test_rmse <- sqrt(rf.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
rf.train_mae <- mean(abs(rf.train_predictions$predictions - train_data$int_rate))
rf.test_mae <- mean(abs(rf.test_predictions$predictions - test_data$int_rate))
# calculate R-squared (R²) for training and testing
rf.train_r2 <- 1 - (sum((train_data$int_rate - rf.train_predictions$predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
rf.test_r2 <- 1 - (sum((test_data$int_rate - rf.test_predictions$predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# display the metrics
cat("Training MSE:", rf.train_mse, "\n")
Training MSE: 2.075461
cat("Testing MSE:", rf.test_mse, "\n")
Testing MSE: 8.69482
cat("Training RMSE:", rf.train_rmse, "\n")
Training RMSE: 1.440646
cat("Testing RMSE:", rf.test_rmse, "\n")
Testing RMSE: 2.948698
cat("Training MAE:", rf.train_mae, "\n")
Training MAE: 1.132674
cat("Testing MAE:", rf.test_mae, "\n")
Testing MAE: 2.331985
cat("Training R-squared (R²):", rf.train_r2, "\n")
Training R-squared (R²): 0.8919301
cat("Testing R-squared (R²):", rf.test_r2, "\n")
Testing R-squared (R²): 0.5470498
Boosting
#### Boosting ####
# define the target variable for training and testing
xgb.y_train <- train_data$int_rate
xgb.y_test <- test_data$int_rate
# define the feature matrix for training and testing (exclude the target variable)
xgb.X_train <- train_data[, -which(names(train_data) == 'int_rate')]
xgb.X_test <- test_data[, -which(names(test_data) == 'int_rate')]
# fit a gradient boosting regression model using xgboost
xgb <- xgboost(
data = as.matrix(xgb.X_train),
label = xgb.y_train,
nrounds = 100,
verbose = 0
)
# make predictions on the training and testing data
xgb.train_predictions <- predict(xgb, newdata = as.matrix(xgb.X_train))
xgb.test_predictions <- predict(xgb, newdata = as.matrix(xgb.X_test))
# calculate Mean Squared Error (MSE) for training and testing
xgb.train_mse <- mean((xgb.train_predictions - xgb.y_train)^2)
xgb.test_mse <- mean((xgb.test_predictions - xgb.y_test)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
xgb.train_rmse <- sqrt(xgb.train_mse)
xgb.test_rmse <- sqrt(xgb.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
xgb.train_mae <- mean(abs(xgb.train_predictions - xgb.y_train))
xgb.test_mae <- mean(abs(xgb.test_predictions - xgb.y_test))
# calculate R-squared (R²) for training and testing
xgb.train_r2 <- 1 - (sum((xgb.y_train - xgb.train_predictions)^2) / sum((xgb.y_train - mean(xgb.y_train))^2))
xgb.test_r2 <- 1 - (sum((xgb.y_test - xgb.test_predictions)^2) / sum((xgb.y_test - mean(xgb.y_test))^2))
# display the metrics
cat("Training MSE:", xgb.train_mse, "\n")
Training MSE: 7.708131
cat("Testing MSE:", xgb.test_mse, "\n")
Testing MSE: 8.015791
cat("Training RMSE:", xgb.train_rmse, "\n")
Training RMSE: 2.776352
cat("Testing RMSE:", xgb.test_rmse, "\n")
Testing RMSE: 2.831217
cat("Training MAE:", xgb.train_mae, "\n")
Training MAE: 2.178155
cat("Testing MAE:", xgb.test_mae, "\n")
Testing MAE: 2.220999
cat("Training R-squared (R²):", xgb.train_r2, "\n")
Training R-squared (R²): 0.5986354
cat("Testing R-squared (R²):", xgb.test_r2, "\n")
Testing R-squared (R²): 0.5824233
Following, a scatter plot of actual vs predicted training values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # add a diagonal reference line
labs(x = "Actual Training Values", y = "Predicted Training Values", title = model_name) +
theme_minimal() +
ylim(-50, 50)
return(scatter_plot)
}
# create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Following, a scatter plot of actual vs predicted testing values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # add a diagonal reference line
labs(x = "Actual Testing Values", y = "Predicted Testing Values", title = model_name) +
theme_minimal() +
ylim(-50, 50) +
xlim(0, 40)
return(scatter_plot)
}
# create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = test_data$int_rate,
predicted_values = lm.test_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = test_data$int_rate,
predicted_values = rf.test_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_test,
predicted_values = xgb.test_predictions,
model_name = "XGBoost"
)
# display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Residual plots can help identify patterns in prediction errors and assess whether the assumptions of linear regression (if applicable) are met.
# create a residual plot function
create_residual_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(
Predicted = predicted_values,
Residuals = residuals
)
residual_plot <- ggplot(residual_data, aes(x = Predicted, y = Residuals)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed", color = "red") + # Red horizontal reference line
labs(x = "Predicted Values", y = "Residuals", title = paste("Residual Plot -", model_name)) +
theme_minimal() +
ylim(-30, 30) +
xlim(0, 40)
return(residual_plot)
}
# create residual plots for each model
lm_residual_plot <- create_residual_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_plot <- create_residual_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_plot <- create_residual_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# display the residual plots separately
print(lm_residual_plot)
print(rf_residual_plot)
print(xgb_residual_plot)
# create a density plot function for residuals
create_residual_density_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
density_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_density(fill = "skyblue", color = "black", alpha = 0.7) +
labs(x = "Residuals", y = "Density", title = paste("Residual Density Plot -", model_name)) +
theme_minimal() +
xlim(-30,30) +
ylim(0, 0.35)
return(density_plot)
}
# create density plots for residuals for each model
lm_residual_density_plot <- create_residual_density_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_density_plot <- create_residual_density_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_density_plot <- create_residual_density_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# display the density plots separately
print(lm_residual_density_plot)
print(rf_residual_density_plot)
print(xgb_residual_density_plot)
This visualization can help you compare the distribution of prediction errors across models through histograms.
# create a histogram plot function for residuals with a red density curve
create_residual_histogram_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
histogram_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_histogram(aes(y = after_stat(density)), bins = 30, fill = "skyblue", color = "black", alpha = 0.7) + # use density on the y-axis for the histogram
geom_density(color = "red", linewidth = 1.5) + # add the density plot in red
labs(x = "Residuals", y = "Density", title = paste("Residual Histogram Plot with Density Curve -", model_name)) +
theme_minimal() +
xlim(-20,20) +
ylim(0, 0.3)
return(histogram_plot)
}
# create histogram plots for residuals for each model
lm_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# display the histogram plots separately
print(lm_residual_histogram_plot)
print(rf_residual_histogram_plot)
print(xgb_residual_histogram_plot)
For each model a bar chart that displays the R-squared (coefficient of determination) values is created. R-squared measures the proportion of variance in the target variable explained by the model. Higher R-squared values indicate better model fit.
# create a data frame with R-squared values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost")
r_squared_values_train <- c(
lm.train_r2,
rf.train_r2,
xgb.train_r2
)
r_squared_values_test <- c(
lm.test_r2,
rf.test_r2,
xgb.test_r2
)
r_squared_data_train <- data.frame(Model = factor(model_names),
R_squared = r_squared_values_train)
r_squared_data_test <- data.frame(Model = factor(model_names),
R_squared = r_squared_values_test)
# create the R-squared comparison bar chart
r_squared_bar_chart_train <- ggplot(r_squared_data_train, aes(x = Model, y = R_squared, fill = Model)) +
geom_bar(stat = "identity") +
labs(x = "Model", y = "R-squared (R²)", title = "R-squared Comparison Training") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0,1)
r_squared_bar_chart_test <- ggplot(r_squared_data_test, aes(x = Model, y = R_squared, fill = Model)) +
geom_bar(stat = "identity") +
labs(x = "Model", y = "R-squared (R²)", title = "R-squared Comparison Testing") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0,1)
# display the R-squared comparison bar chart
print(r_squared_bar_chart_train)
print(r_squared_bar_chart_test)
A bar chart that compares the MAE or RMSE values, is generated for each model. These metrics quantify the average prediction errors of each model, and lower values are preferred.
# create a data frame with MAE and RMSE values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost","Linear Regression", "Random Forest", "XGBoost")
error_values_train <- c(
lm.train_mae,
rf.train_mae,
xgb.train_mae,
lm.train_rmse,
rf.train_rmse,
xgb.train_rmse
)
error_values_test <- c(
lm.test_mae,
rf.test_mae,
xgb.test_mae,
lm.test_rmse,
rf.test_rmse,
xgb.test_rmse
)
error_type <- c(
"MAE", "MAE", "MAE","RMSE","RMSE","RMSE"
)
model_errors_train <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_train, Type = error_type)
model_errors_test <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_test, Type = error_type)
# create the MAE or RMSE comparison bar chart
error_bar_chart_train <- ggplot(model_errors_train, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Training MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
error_bar_chart_test <- ggplot(model_errors_test, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Testing MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
# display the MAE and RMSE comparison bar chart
print(error_bar_chart_train)
print(error_bar_chart_test)
#### Random Forest Feature Importance Plot ####
v1 <- vip(rf, title = "Ranger", num_features = 20)
plot(v1)
Feature Selection from the variable importance’s analysis:
imp.variables <- lc_data[, v1$data$Variable]
imp.variables$int_rate <- lc_data$int_rate
imp.train_indices <- createDataPartition(imp.variables$int_rate, p = 0.8, list = FALSE)
# create training and testing datasets
imp.train_data <- imp.variables[imp.train_indices, ]
imp.test_data <- imp.variables[-imp.train_indices, ]
#### Linear Regression with only importance variables ####
imp.lm.fit <- lm(int_rate ~ ., data = imp.train_data)
# make predictions on the training and testing data
imp.lm.train_predictions <- predict(imp.lm.fit, newdata = imp.train_data)
imp.lm.test_predictions <- predict(imp.lm.fit, newdata = imp.test_data)
# calculate Mean Squared Error (MSE) for training and testing
imp.lm.train_mse <- mean((imp.lm.train_predictions - imp.train_data$int_rate)^2)
imp.lm.test_mse <- mean((imp.lm.test_predictions - imp.test_data$int_rate)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
imp.lm.train_rmse <- sqrt(imp.lm.train_mse)
imp.lm.test_rmse <- sqrt(imp.lm.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
imp.lm.train_mae <- mean(abs(imp.lm.train_predictions - imp.train_data$int_rate))
imp.lm.test_mae <- mean(abs(imp.lm.test_predictions - imp.test_data$int_rate))
# calculate R-squared (R²) for training and testing
imp.lm.train_r2 <- 1 - (sum((imp.train_data$int_rate - imp.lm.train_predictions)^2) / sum((imp.train_data$int_rate - mean(imp.train_data$int_rate))^2))
imp.lm.test_r2 <- 1 - (sum((imp.test_data$int_rate - imp.lm.test_predictions)^2) / sum((imp.test_data$int_rate - mean(imp.test_data$int_rate))^2))
# display the metrics
cat("Training MSE:", imp.lm.train_mse, "\n")
Training MSE: 10.86566
cat("Testing MSE:", imp.lm.test_mse, "\n")
Testing MSE: 10.99868
cat("Training RMSE:", imp.lm.train_rmse, "\n")
Training RMSE: 3.29631
cat("Testing RMSE:", imp.lm.test_rmse, "\n")
Testing RMSE: 3.316426
cat("Training MAE:", imp.lm.train_mae, "\n")
Training MAE: 2.61514
cat("Testing MAE:", imp.lm.test_mae, "\n")
Testing MAE: 2.613664
cat("Training R-squared (R²):", imp.lm.train_r2, "\n")
Training R-squared (R²): 0.4346627
cat("Testing R-squared (R²):", imp.lm.test_r2, "\n")
Testing R-squared (R²): 0.425238
#### Random Forest with only importance variables ####
# train a Random Forest model
imp.rf <- ranger(formula = int_rate ~ ., data = imp.train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
Growing trees.. Progress: 21%. Estimated remaining time: 1 minute, 59 seconds.
Growing trees.. Progress: 42%. Estimated remaining time: 1 minute, 26 seconds.
Growing trees.. Progress: 64%. Estimated remaining time: 53 seconds.
Growing trees.. Progress: 85%. Estimated remaining time: 22 seconds.
# print the model summary
print("Random Forest Model Summary:")
[1] "Random Forest Model Summary:"
print(imp.rf)
Ranger result
Call:
ranger(formula = int_rate ~ ., data = imp.train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 20
Mtry: 4
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.743306
R squared (OOB): 0.5450889
# make predictions on the training and testing data
imp.rf.train_predictions <- predict(imp.rf, data = imp.train_data)
imp.rf.test_predictions <- predict(imp.rf, data = imp.test_data)
# calculate Mean Squared Error (MSE) for training and testing
imp.rf.train_mse <- mean((imp.rf.train_predictions$predictions - imp.train_data$int_rate)^2)
imp.rf.test_mse <- mean((imp.rf.test_predictions$predictions - imp.test_data$int_rate)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
imp.rf.train_rmse <- sqrt(imp.rf.train_mse)
imp.rf.test_rmse <- sqrt(imp.rf.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
imp.rf.train_mae <- mean(abs(imp.rf.train_predictions$predictions - imp.train_data$int_rate))
imp.rf.test_mae <- mean(abs(imp.rf.test_predictions$predictions - imp.test_data$int_rate))
# calculate R-squared (R²) for training and testing
imp.rf.train_r2 <- 1 - (sum((imp.train_data$int_rate - imp.rf.train_predictions$predictions)^2) / sum((imp.train_data$int_rate - mean(imp.train_data$int_rate))^2))
imp.rf.test_r2 <- 1 - (sum((test_data$int_rate - rf.test_predictions$predictions)^2) / sum((imp.test_data$int_rate - mean(imp.test_data$int_rate))^2))
# display the metrics
cat("Training MSE:", imp.rf.train_mse, "\n")
Training MSE: 1.714178
cat("Testing MSE:", imp.rf.test_mse, "\n")
Testing MSE: 8.674378
cat("Training RMSE:", imp.rf.train_rmse, "\n")
Training RMSE: 1.309266
cat("Testing RMSE:", imp.rf.test_rmse, "\n")
Testing RMSE: 2.94523
cat("Training MAE:", imp.rf.train_mae, "\n")
Training MAE: 1.02214
cat("Testing MAE:", imp.rf.test_mae, "\n")
Testing MAE: 2.329954
cat("Training R-squared (R²):", imp.rf.train_r2, "\n")
Training R-squared (R²): 0.9108118
cat("Testing R-squared (R²):", imp.rf.test_r2, "\n")
Testing R-squared (R²): 0.5456317
#### Boosting with only importance variables ####
# define the target variable for training and testing
imp.xgb.y_train <- imp.train_data$int_rate
imp.xgb.y_test <- imp.test_data$int_rate
# define the feature matrix for training and testing (exclude the target variable)
imp.xgb.X_train <- imp.train_data[, -which(names(imp.train_data) == 'int_rate')]
imp.xgb.X_test <- imp.test_data[, -which(names(imp.test_data) == 'int_rate')]
# fit a gradient boosting regression model using xgboost
imp.xgb <- xgboost(
data = as.matrix(imp.xgb.X_train),
label = imp.xgb.y_train,
nrounds = 100,
verbose = 0
)
# make predictions on the training and testing data
imp.xgb.train_predictions <- predict(imp.xgb, newdata = as.matrix(imp.xgb.X_train))
imp.xgb.test_predictions <- predict(imp.xgb, newdata = as.matrix(imp.xgb.X_test))
# calculate Mean Squared Error (MSE) for training and testing
imp.xgb.train_mse <- mean((imp.xgb.train_predictions - imp.xgb.y_train)^2)
imp.xgb.test_mse <- mean((imp.xgb.test_predictions - imp.xgb.y_test)^2)
# calculate Root Mean Squared Error (RMSE) for training and testing
imp.xgb.train_rmse <- sqrt(imp.xgb.train_mse)
imp.xgb.test_rmse <- sqrt(imp.xgb.test_mse)
# calculate Mean Absolute Error (MAE) for training and testing
imp.xgb.train_mae <- mean(abs(imp.xgb.train_predictions - imp.xgb.y_train))
imp.xgb.test_mae <- mean(abs(imp.xgb.test_predictions - imp.xgb.y_test))
# calculate R-squared (R²) for training and testing
imp.xgb.train_r2 <- 1 - (sum((imp.xgb.y_train - imp.xgb.train_predictions)^2) / sum((imp.xgb.y_train - mean(imp.xgb.y_train))^2))
imp.xgb.test_r2 <- 1 - (sum((imp.xgb.y_test - imp.xgb.test_predictions)^2) / sum((imp.xgb.y_test - mean(imp.xgb.y_test))^2))
# display the metrics
cat("Training MSE:", imp.xgb.train_mse, "\n")
Training MSE: 7.75411
cat("Testing MSE:", imp.xgb.test_mse, "\n")
Testing MSE: 8.068693
cat("Training RMSE:", imp.xgb.train_rmse, "\n")
Training RMSE: 2.78462
cat("Testing RMSE:", imp.xgb.test_rmse, "\n")
Testing RMSE: 2.840544
cat("Training MAE:", imp.xgb.train_mae, "\n")
Training MAE: 2.186026
cat("Testing MAE:", imp.xgb.test_mae, "\n")
Testing MAE: 2.231548
cat("Training R-squared (R²):", imp.xgb.train_r2, "\n")
Training R-squared (R²): 0.5965558
cat("Testing R-squared (R²):", imp.xgb.test_r2, "\n")
Testing R-squared (R²): 0.5783514
The dataset was filtered by the 20 variables with the most importance (from the rf results). As we can see above, the errors of each model are more or less the errors with the double variables we had before, so filtering by these 20 “important variables” does not seem making sense…
Hyperparameter Tuning for XGBoosting: